package com.ys.controller.api.outer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAccessTokenCacheImpl;
import com.amazon.spapi.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.LWAClientScopes;
import com.amazon.spapi.api.NotificationsApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.notifications.*;
import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper;
import com.amazon.sqs.javamessaging.ProviderConfiguration;
import com.amazon.sqs.javamessaging.SQSConnection;
import com.amazon.sqs.javamessaging.SQSConnectionFactory;
import com.squareup.okhttp.Call;
import com.ys.config.MyConfig;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.RegionEnum;
import com.ys.mapper.business.TsCorresLogMapper;
import com.ys.util.HttpUtilYs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;

import javax.jms.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.amazon.SellingPartnerAPIAA.ScopeConstants.SCOPE_MIGRATION_API;
import static com.amazon.SellingPartnerAPIAA.ScopeConstants.SCOPE_NOTIFICATIONS_API;

/**
 * @Author: fxz
 * @CreateTime: 2024-09-18
 * @Description: 亚马逊aws队列
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/outer/demoFXZAwsSqs")
public class ApiOuterDemoFXZAwsSqsController {

    @Autowired
    private TsCorresLogMapper tsCorresLogMapper;

    /**
     * 创建 createDestination
     */
    @RequestMapping("/test8")
    @ResponseBody
    public void test8() {
        List<Map<String, Object>> tpAmazonSellerList = new TpAmazonSeller()
                .addLeftJoin("TP_AmazonRegion tar on tar.Code = A.regionCode")//平台地区
                .addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
                .where("A.authorizeState = '已授权'" + "AND A.vgsbm = '" + "GS0075" +"'")
                .setStatus(1)
                .queryMap();
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonSellerList));
        JSONObject jsonObject = jsonArray.getJSONObject(0);

        LWAClientScopes lwaClientScopes = new LWAClientScopes(new HashSet<>());
        lwaClientScopes.getScopes().add("sellingpartnerapi::notifications");
        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId(MyConfig.getAmazonLwaClientKey())
                .clientSecret(MyConfig.getAmazonLwaClientSecret())
                .endpoint(MyConfig.getAmazonLwaEndpoint())
                .scopes(lwaClientScopes)
//                .refreshToken(jsonObject.get("refreshToken").toString())
                .build();

        AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                .roleArn(MyConfig.getAmazonRoleArn())
                .roleSessionName(MyConfig.getAmazonRoleSessionName())
                .build();

        AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                .accessKeyId(MyConfig.getAmazonAwsAccessKey())
                .secretKey(MyConfig.getAmazonAwsAccessSecret())
                .region(jsonObject.get("awsRegion").toString())
                .build();

        NotificationsApi notificationsApi = new NotificationsApi.Builder()
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .endpoint("https://sellingpartnerapi-eu.amazon.com")
                .build();

        DestinationResourceSpecification destinationResourceSpecification = new DestinationResourceSpecification();
        SqsResource sqsResource = new SqsResource();
//        sqsResource.setArn("arn:aws:sqs:us-east-1:107584446982:EASEkeji");
        sqsResource.setArn("arn:aws:sqs:eu-west-1:107584446982:EASEkeji");
        destinationResourceSpecification.setSqs(sqsResource);
        CreateDestinationRequest body = new CreateDestinationRequest();
        body.setResourceSpecification(destinationResourceSpecification);
        body.setName("EASEkeji");
        try {
            CreateDestinationResponse destination = notificationsApi.createDestination(body);
            destination = destination;
            System.out.println(destination);
//            3b3dd81a-847b-4547-8099-4a321c34b698
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据 Destination 创建订阅
     */
    @RequestMapping("/test11")
    @ResponseBody
    public void test11() {
        String accessKeyId = "AKIARSDEIMIDO3KIQJH6";

        String secretKey = "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";

        SqsClient sqsClient = SqsClient.builder().region(Region.US_EAST_1)
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("" +
                        accessKeyId, secretKey)))
                .build();
//         Create a new connection factory with all defaults (credentials and region) set automatically
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),  sqsClient
        );

        // Create the connection.
        try {
            SQSConnection connection = connectionFactory.createConnection();
            AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();
            if (!client.queueExists("EASEkeji")) {
                System.out.println(123);
            }
            System.out.println(1234);

            // Create the nontransacted session with AUTO_ACKNOWLEDGE mode
            // 通过这个方法直接确认消息已经被接受不需要在传输过来
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

            // Create a queue identity and specify the queue name to the session
            Queue queue = session.createQueue("EASEkeji");

            // Create a consumer for the 'EASEkeji'
            MessageConsumer consumer = session.createConsumer(queue);
            // Start receiving incoming messages
            connection.start();

            // Receive a message from 'MyQueue' and wait up to 1 second
            Message receivedMessage = consumer.receive(1000);

//            // Cast the received message as TextMessage and display the text
//            if (receivedMessage != null) {
//                System.out.println("Received: " + ((TextMessage) receivedMessage).getText());
//            }
            // Cast the received message as TextMessage and print the text to screen. Also acknowledge the message.
            if (receivedMessage != null) {
                System.out.println("Received: " + ((TextMessage) receivedMessage).getText());
                receivedMessage.acknowledge();
            }

            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        }


//        // Create a consumer for the 'MyQueue'
//        MessageConsumer consumer = session.createConsumer(queue);
//// Start receiving incoming messages
//        connection.start();


    }

    /**
     * 根据 Destination 创建订阅
     */
    @RequestMapping("/test7")
    @ResponseBody
    public void test7() {
        List<Map<String, Object>> tpAmazonSellerList = new TpAmazonSeller()
                .addLeftJoin("TP_AmazonRegion tar on tar.Code = A.regionCode")//平台地区
                .addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
                .where("A.authorizeState = '已授权'" + "AND A.vgsbm = '" + "GS0075" +"'")
                .setStatus(1)
                .queryMap();
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonSellerList));
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId(MyConfig.getAmazonLwaClientKey())
                .clientSecret(MyConfig.getAmazonLwaClientSecret())
                .endpoint(MyConfig.getAmazonLwaEndpoint())
                .refreshToken(jsonObject.get("refreshToken").toString())
                .build();

        AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                .roleArn(MyConfig.getAmazonRoleArn())
                .roleSessionName(MyConfig.getAmazonRoleSessionName())
                .build();

        AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                .accessKeyId(MyConfig.getAmazonAwsAccessKey())
                .secretKey(MyConfig.getAmazonAwsAccessSecret())
                .region(jsonObject.get("awsRegion").toString())
                .build();

        NotificationsApi notificationsApi = new NotificationsApi.Builder()
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .endpoint("https://sellingpartnerapi-eu.amazon.com")
                .build();

        CreateSubscriptionRequest request = new CreateSubscriptionRequest();
        request.setDestinationId("3b3dd81a-847b-4547-8099-4a321c34b698");
        request.setPayloadVersion("1.0");
        try {
//            CreateSubscriptionResponse subscription = notificationsApi.createSubscription(request,"REPORT_PROCESSING_FINISHED" );
            DeleteSubscriptionByIdResponse report_processing_finished = notificationsApi.deleteSubscriptionById("61fa1157-bbd2-495f-ace4-d8698a305074", "REPORT_PROCESSING_FINISHED");
            DeleteDestinationResponse deleteDestinationResponse = notificationsApi.deleteDestination("3b3dd81a-847b-4547-8099-4a321c34b698");
            deleteDestinationResponse = deleteDestinationResponse;
//            subscription = subscription;
//            class Subscription {
//                subscriptionId: 61fa1157-bbd2-495f-ace4-d8698a305074
//                payloadVersion: 1.0
//                destinationId: 3b3dd81a-847b-4547-8099-4a321c34b698
//            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }



    /**
     * 轮询秘钥
     */
    @RequestMapping("/test12")
    @ResponseBody
    public void test12() {
        TbStaticConfig tbStaticConfig1 = new TbStaticConfig().setKeyOne("amazon-spapi-lwa-client_id").queryFirst();
        TbStaticConfig tbStaticConfig2 = new TbStaticConfig().setKeyOne("amazon-spapi-lwa-client_secret").queryFirst();
        TbStaticConfig tbStaticConfig3 = new TbStaticConfig().setKeyOne("amazon-spapi-lwa-end_point").queryFirst();

        Map<String, String> postMapParams = new HashMap<>();
        postMapParams.put("grant_type", "client_credentials");
        postMapParams.put("scope", "sellingpartnerapi::client_credential:rotation");
        postMapParams.put("client_id", tbStaticConfig1.getName());
        postMapParams.put("client_secret", tbStaticConfig2.getName());

        System.out.println(JSON.toJSONString(postMapParams));

        String urlNotify = tbStaticConfig3.getName();
//        {"access_token":"Atc|MQEBIEerR31msquxd0eR9wTyUTVnaFpC71wQJG4phi14L554dZF6i8P6ZMwymXe370ltgJRpdjCsJ-IWT1OUfXv74jlkEzefmgjBLbtLtY6_kTltV50pIKQFTqxWuiTKdBdgWJnUN0Fvpy4oKsbk-OPEO-iJxZ7_uwzCV4felej3OUV9HnBJqBsMC3oQOox_MWNCQEq9SXQs0JnJQ_gGzD6OUAk--G87DfXHn2mmZnHZa6vdsJnKM6gNCM8PE_35mVNLpm7v7K4-LZmj_c9ACuHbkMrw","scope":"sellingpartnerapi::client_credential:rotation","token_type":"bearer","expires_in":3600}
        String result = HttpUtilYs.sendHttpClientPost(urlNotify, postMapParams);
        System.out.println(result);
        JSONObject resultJO = JSON.parseObject(result);
        String access_token = resultJO.getString("access_token");

        RegionEnum regionEnum = RegionEnum.from("NORTH");


//        com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials lwaAuthorizationCredentials = com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials.builder()
//                .clientId(MyConfig.getAmazonLwaClientKey())
//                .clientSecret(MyConfig.getAmazonLwaClientSecret())
//                .endpoint(MyConfig.getAmazonLwaEndpoint())
//                .withScopes(SCOPE_NOTIFICATIONS_API,SCOPE_MIGRATION_API)
//                .build();
//        LWAAccessTokenCacheImpl lwaAccessTokenCache =  new LWAAccessTokenCacheImpl();
//        lwaAccessTokenCache.put("x-amz-access-token",access_token,3600);
//
//        ApplicationsApi applicationsApi = new ApplicationsApi.Builder()
//                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
//                .endpoint(regionEnum.getServiceUrl())
//                .lwaAccessTokenCache(lwaAccessTokenCache)
//                .build();
//        try {
////            postMapParams = new HashMap<>();
////            postMapParams.put("Content-Length", "0");
////            postMapParams.put("Host", "<calculated when request is sent>");
////            postMapParams.put("User-AgentAccept", "PostmanRuntime/7.36.0");
////            postMapParams.put("Accept", "*/*");
////            postMapParams.put("Accept-Encoding", "gzip, deflate, br");
////            postMapParams.put("Connection", "keep-alive");
////            postMapParams.put("x-amz-access-token", access_token);
////            System.out.println(JSON.toJSONString(postMapParams));
//
////             urlNotify = "https://sellingpartnerapi-na.amazon.com/applications/2023-11-30/clientSecret";
////             result = HttpUtilYs.sendHttpClientPost(urlNotify, postMapParams);
////            System.out.println(result);
////             resultJO = JSON.parseObject(result);
//            applicationsApi.rotateApplicationClientSecret();
//            System.out.println("成功");
//        }catch (Exception e){
//            System.out.println(e.getMessage());
//        }
    }

}
